package com.wgc.oauth.controller;

import com.wgc.entity.Result;
import com.wgc.oauth.service.AuthService;
import com.wgc.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 认证中心
 */
@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @Autowired
    private AuthService authService;

    /**
     * 登录接口
     * @RequestBody Map<String,String> paramMap
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map<String,String> paramMap){
        String username = paramMap.get("username");
        String password = paramMap.get("password");
        Map login = null;
        try {
            login = authService.login(username,password,clientId,clientSecret);
        } catch (Exception e) {
            return Result.fail(e);
        }
        this.saveJtiToCookie(login.get("jti").toString());
        return new Result("登录成功",login);
    }

    private void saveJtiToCookie(String jti) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response, cookieDomain, "/", "token", jti, cookieMaxAge, false);
    }


}

